﻿using System;
using System.Collections.Generic;

namespace 面向对象_索引器3
{
    class Program
    {
        static void Main(string[] args)
        {
            // 生成 dog 对象
            var dog = new Dog("猪", 2, 180);
            var son1 = new Dog("黑猪",1 , 150);
            var son2 = new Dog("黑猪", 1, 100);

            int age = 1;
            string name = "黑猪";


            //将 son1 录入到 dog 的户口本
            dog[age, name] = son1;

            Console.WriteLine($"Before  {dog[age, name]}");

            // 发现抱错孩子，交换
            dog[age, name] = son2;

            // 证明真的交换了吗？
            Console.WriteLine($"After  {dog[age, name]}");
        }
    }
    //索引器的重载使用virtual关键字
    class person
    {
        private string[] arr;
        public virtual string this[int index]
        {
            get { return arr[index]; }
            set { arr[index] = value; }
        }
    }
    class persons : person
    {
        private string[] arr2;
        public override string this[int index] { get => arr2[index]; set => base[index] = value; }
    }
    //多参数索引器
    class SurperMan
    {
        private int[,] arr;
        public SurperMan(int x, int y)
        {
            arr = new int[x, y];
        }

        // 在本例，x、y 是索引值
        public int this[int x, int y]
        {
            get
            {
                // todo : x 钳制，y 钳制
                var data = arr[x, y];

                return data;
            }
        }
    }
    class Dog
    {
        private string name;
        private int age;
        private int size;//身高大小
        private List<Dog> family;
        public Dog(string name, int age, int size)//初始化对象
        {
            this.name = name;
            this.age = age;
            this.size = size;
            family = new List<Dog>();
        }
        public Dog this[int age, string name]
        {
            get
            {
                //查看断言是否成立
                var dog = family.Find(v => v.age == age && v.name == name);
                return dog;
            }
            set
            {
                //Findindex返回查找内容在列表中的位置，find返回参数相同类型的对象。
                var index = family.FindIndex(v => v.age == age && v.name == name);
                if (index == -1)
                {
                    family.Add(value);
                }
                else
                {
                    family[index] = value;
                }
            }
        }
        public override string ToString()
        {
            return size.ToString();
        }
    }
}

